<?php
/**
 * Model base class.
 * 
 * @package EICms
 * @subpackage Model
 * @author hcderaad
 */
/**
 * Model base class.
 *
 * @package EICms
 * @subpackage Model
 * @author hcderaad
 */
class EICms_Model implements EICms_Model_Interface {
	
	/**
	 * The table
	 *
	 * @var EICms_Table
	 */
	protected $table;
	
	/**
	 * Returns a list of records.
	 *
	 * @param Zend_Db_Select $select
	 * @return array
	 */
	public function fetchList(Zend_Db_Select $select = null) {
		if(!$select instanceof Zend_Db_Select) {
			$select = $this->table->select();
		}
		$fieldArr = array();
		foreach($this->table->getListFields() as $field) {
			$fieldArr[] = $this->table->getAdapter()->quoteIdentifier($this->table->getTableName()) . '.' . 
							$this->table->getAdapter()->quoteIdentifier($field);
		}
		if(!$select->getPart(Zend_Db_Select::FROM)) {
			$labelExpr = new Zend_Db_Expr('CONCAT_WS(", ",' . implode(', ',$fieldArr) . ') ' . ' AS ' . $this->table->getAdapter()->quoteIdentifier('listLabelExpr'));
			$primary = $this->table->getPrimary();
			$primary = reset($primary);
			$table = $this->table->getTableName();
			$select->from($table,array($primary,$labelExpr));
		}
		if(!$select->getPart(Zend_Db_Select::ORDER)) {
			$select->order($this->table->getListFields());
		}
		return $this->table->getAdapter()->fetchPairs($select);
	}
	
	/**
	 * Returns a list of active records, if the table contains a status field (if not a complete list is returned).
	 *
	 * @param Zend_Db_Select $select
	 * @return array
	 */
	public function fetchListActive(Zend_Db_Select $select = null) {
		if(!$select instanceof Zend_Db_Select) {
			$select = $this->table->select();
		}
		$info = $this->table->info();
		if(in_array('status',$info['cols'])) {
			$select->where($this->table->getAdapter()->quoteIdentifier($this->table->getTableName()) . 
							$this->table->getAdapter()->quoteIdentifier('status') . ' = ?',1);
		}
		return $this->fetchList($select);
	}
	
	/**
	 * Returns a select object.
	 *
	 * @return Zend_Db_Select
	 */
	public function select() {
		return $this->table->select();
	}
	
	/**
	 * Returns the table object.
	 *
	 * @return EICms_Table
	 */
	public function getTable() {
		return $this->table;
	}
	
	/**
	 * Quotes a value
	 *
	 * @param string $string
	 * @return string
	 */
	public function quote($string) {
		return $this->table->getAdapter()->quote($string);
	}
	
	/**
	 * Quotes a value into a string
	 *
	 * @param string $string
	 * @param mixed $var
	 * @return string
	 */
	public function quoteInto($string,$var) {
		return $this->table->getAdapter()->quoteInto($string,$var);
	}
	
	/**
	 * Quotes an identifier
	 *
	 * @param string $string
	 * @return string
	 */
	public function quoteIdentifier($string) {
		return $this->table->getAdapter()->quoteIdentifier($string);
	}
}
?>